/*
 * Copyright (C) 2011-2014 GUIGUI Simon, fyhertz@gmail.com
 * 
 * This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
 * 
 * Spydroid is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This source code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this source code; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package net.majorkernelpanic.streaming.audio;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;

import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.rtp.AMRNBPacketizer;
import net.majorkernelpanic.streaming.rtp.MediaCodecInputStream;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.media.audiofx.AcousticEchoCanceler;
import android.media.audiofx.NoiseSuppressor;
import android.os.Build;
import android.service.textservice.SpellCheckerService.Session;
import android.util.Log;

/**
 * A class for streaming AAC from the camera of an android device using RTP.
 * You should use a {@link Session} instantiated with {@link SessionBuilder} instead of using this class directly.
 * Call {@link #setDestinationAddress(InetAddress)}, {@link #setDestinationPorts(int)} and {@link #setAudioQuality(AudioQuality)}
 * to configure the stream. You can then call {@link #start()} to start the RTP stream.
 * Call {@link #stop()} to stop the stream.
 */
public class AMRNBStream extends AudioStream {

	// TODO
	private AudioRecord mAudioRecord = null;
	private Thread mThread = null;
		
	public AMRNBStream() {
		super();

		// TODO
        if (!AMRStreamingSupported()) {
            Log.e(TAG,"AMR not supported on this phone");
            throw new RuntimeException("AMR not supported by this phone !");
        } else {
            Log.d(TAG,"AMR supported on this phone");
        }
        
		mPacketizer = new AMRNBPacketizer();

		setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
		
		try {
			// RAW_AMR was deprecated in API level 16.
			Field deprecatedName = MediaRecorder.OutputFormat.class.getField("RAW_AMR");
			setOutputFormat(deprecatedName.getInt(null));
		} catch (Exception e) {
			setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
		}
		
		setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		
	}

	// TODO
	//����Ƿ�֧��AMR
    private boolean AMRStreamingSupported() {
        if (Build.VERSION.SDK_INT < 16)
            return false;
        try {
            //������ƣ�getField
            //MediaRecorder.OutputFormat.class.getField("AAC_ADTS");
            MediaRecorder.OutputFormat.class.getField("RAW_AMR");
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
	/**
	 * Starts the stream.
	 */
	public synchronized void start() throws IllegalStateException, IOException {
		if (!mStreaming) {
			configure();
			super.start();
		}
	}

	public synchronized void configure() throws IllegalStateException, IOException {
		super.configure();
		//mMode = MODE_MEDIARECORDER_API;	// ִ��encodeWithMediaRecorder����
		mMode = MODE_MEDIACODEC_API;		// ִ��encodeWithMediaCodec����
		mQuality = mRequestedQuality.clone();
	}

	/**
	 * Returns a description of the stream using SDP. It can then be included in an SDP file.
	 */	
	public String getSessionDescription() {
		return "m=audio "+String.valueOf(getDestinationPorts()[0])+" RTP/AVP 96\r\n" +
				"a=rtpmap:96 AMR/8000\r\n" +
				"a=fmtp:96 octet-align=1;\r\n";
	}

	// TODO
	protected void encodeWithMediaRecorder() throws IOException {
		//super.encodeWithMediaRecorder();
		encodeWithMediaCodec();
	}
	
	// TODO
	protected void encodeWithMediaCodec() throws IOException {
		final int bufferSize = AudioRecord.getMinBufferSize(
				mQuality.samplingRate,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        // MediaRecorder.AudioSource.MIC --> MediaRecorder.AudioSource.VOICE_COMMUNICATION
        mAudioRecord = new AudioRecord(
                MediaRecorder.AudioSource.VOICE_COMMUNICATION,
                mQuality.samplingRate,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                bufferSize);

        if (isAECAailable()) {
            AcousticEchoCanceler aec = AcousticEchoCanceler
                    .create(mAudioRecord.getAudioSessionId());
            if (aec != null && !aec.getEnabled()) {
                aec.setEnabled(true);
            }
            Log.d("TAG", "AEC-->success");
        }


        if (isNSAvailable()) {
            NoiseSuppressor noise = NoiseSuppressor
                    .create(mAudioRecord.getAudioSessionId());
            if (noise != null && !noise.getEnabled()) {
                noise.setEnabled(true);
            }
            Log.d("TAG", "NS-->success");
        }
        
        //"audio/3gpp" - AMR narrowband audio
        mMediaCodec = MediaCodec.createEncoderByType("audio/3gpp");
        MediaFormat format = new MediaFormat();
        format.setString(MediaFormat.KEY_MIME, "audio/3gpp");
        format.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitRate);
        format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
        format.setInteger(MediaFormat.KEY_SAMPLE_RATE, mQuality.samplingRate);
        format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, bufferSize);
        mMediaCodec.configure(format,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
        mAudioRecord.startRecording();
		mMediaCodec.start();
		
		final MediaCodecInputStream inputStream = new MediaCodecInputStream(mMediaCodec);
		final ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
		
		mThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
                int len = 0, bufferIndex = 0;
                try {
                    while (!Thread.interrupted()) {
                        bufferIndex = mMediaCodec.dequeueInputBuffer(50000);
                        if (bufferIndex >= 0) {
                            inputBuffers[bufferIndex].clear();
                            len = mAudioRecord.read(inputBuffers[bufferIndex], bufferSize);
                            if (len == AudioRecord.ERROR_INVALID_OPERATION || len == AudioRecord.ERROR_BAD_VALUE) {
                                mMediaCodec.queueInputBuffer(bufferIndex, 0, 0, 0, 0);
                            } else {
                                mMediaCodec.queueInputBuffer(bufferIndex, 0, len, 0, 0);
                            }
                        }
                    }
                } catch (RuntimeException e) {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    String stack = sw.toString();
                    Log.i(TAG, "record" + stack);
                }
			}
		});
		mThread.start();
		
		// The packetizer encapsulates this stream in an RTP stream and send it over the network
		mPacketizer.setInputStream(inputStream);
		mPacketizer.start();

		mStreaming = true;
		
	}
	

    private static boolean isAECAailable() {
        return AcousticEchoCanceler.isAvailable();
    }


    private static boolean isNSAvailable() {
        return NoiseSuppressor.isAvailable();		//Call requires API level 16 (current min is 14): �޸�android:minSdkVersion="16"
    }
	

	public synchronized void stop() {
		if (mStreaming) {
			//if (mMode==MODE_MEDIARECORDER_API) {
			if (mMode==MODE_MEDIACODEC_API) {
				Log.d(TAG, "Interrupting threads...");
				mThread.interrupt();
				mAudioRecord.stop();
				mAudioRecord.release();
				mAudioRecord = null;
			}
			super.stop();
		}
	}
}